#!/usr/bin/env python
'''
log management

modification:
	2010-11-29
		因为logger的filepath属性是在加载模块的时候生成的，原代码在此时会直接生成log文件，此次修正此bug

'''

import inspect
import logging
import os
import time

###################################################################################
def __getlogpath():
	'''
	get path of the log file
	'''
	f	= inspect.currentframe().f_back
	while f.f_back and hasattr(f.f_back, 'f_code'):
		f	= f.f_back

	assert f.f_code, 'f(%s) has no attribute f_code'%(f)
	filepath= f.f_code.co_filename

	# In the 'Python Interactive Shell', filepath will be '<stdin>'
	if filepath== '<stdin>':
		filepath	= 'stdin%s'%(os.getpid())
	#print(filepath)

	assert filepath, '%s should be valid'%filepath
	return filepath + '.log'

def __getlogger(logger= []):
	'''
	get the only logger according to the main file
	'''

	if not logger:
		logpath		= __getlogpath()
		lg			= logging.getLogger()
		lg.addHandler(logging.FileHandler(logpath, 'w', encoding= 'utf8'))
		lg.setLevel(logging.NOTSET)
		# add an filepath attribute
		lg.logpath	= logpath
		logger.append(lg)
	
	return logger[0]

def flog(text= None):
	'''
	log text on local files
	'''

	def __getcaller():
		"""
		Find the stack frame of the caller so that we can note the source
		file name, line number and function name.
		"""
		srcfile	= os.path.basename(__file__)
		f		= inspect.currentframe().f_back
		rv		= "(unknown file)", 0, "(unknown function)"
		while hasattr(f, "f_code"):
			co	= f.f_code
			filename= os.path.basename(co.co_filename)
			if filename == srcfile:
				f	= f.f_back
				continue
			rv	= (filename, f.f_lineno, co.co_name)
			break
		return rv
	
	# check if need print text to the console
	if hasattr(flog, 'isprint') and flog.isprint:
		print(text)

	curtime		= time.strftime('%Y-%m-%d %X', time.localtime())
	rv			= __getcaller()

	logger		= __getlogger()
	text		= '[%s %s!%s():%d] %s'%(curtime, rv[0], rv[2], rv[1], text) 
	logger.info(text)

## add some dynamic attribute for flog()
if not hasattr(flog, 'filepath'):
	flog.logpath	= __getlogpath()

###################################################################################

if __name__=='__main__':
	flog('without isprint')
	flog.isprint	= True
	flog('with isprint')
	flog.isprint	= False
	flog('isprint is turnoff')
